package com.situ.mall.web.controller;

import com.category.spi.model.CategoryTreeDTO;
import com.mall.common.util.JsonResult;
import com.mall.user.model.vo.LoginUserVO;
import com.situ.mall.web.service.CategoryFeignService;
import com.situ.mall.web.service.NotificationFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.List;

/**
 * 通知页面控制器
 */
@Slf4j
@Controller
public class NotificationController {

    @Autowired
    private NotificationFeignService notificationFeignService;
    
    @Autowired
    private CategoryFeignService categoryFeignService;

    /**
     * 通知页面
     */
    @GetMapping("/notifications")
    public String notifications(Model model, HttpServletRequest request,
                               @RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "size", defaultValue = "10") Integer size) {
        try {
            // 检查登录状态
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return "redirect:/login";
            }

            // 获取分类数据（用于导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 获取用户通知列表
            try {
                ResponseEntity<JsonResult<?>> notificationsResult = notificationFeignService.getUserNotifications(
                        page, size, currentUser.getId().intValue());
                
                if (notificationsResult.getBody() != null && notificationsResult.getBody().isSuccess()) {
                    model.addAttribute("notifications", notificationsResult.getBody().getData());
                    log.info("获取用户通知列表成功: userId={}, page={}", currentUser.getId(), page);
                } else {
                    model.addAttribute("notifications", java.util.Collections.emptyList());
                }
            } catch (Exception e) {
                log.warn("获取通知列表失败: userId={}", currentUser.getId(), e);
                model.addAttribute("notifications", java.util.Collections.emptyList());
            }

            // 获取未读通知数量（暂时使用模拟数据，需要根据实际API调整）
            model.addAttribute("unreadCount", 0);

            // 分页信息
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("currentUser", currentUser);

        } catch (Exception e) {
            log.error("通知页面数据加载失败", e);
            return "redirect:/login";
        }

        return "notifications";
    }

    /**
     * 标记通知为已读
     */
    @PostMapping("/notifications/mark-read")
    @ResponseBody
    public JsonResult<?> markAsRead(@RequestParam("notificationId") Long notificationId, HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            // 构建更新请求
            java.util.Map<String, Object> updateRequest = new java.util.HashMap<>();
            updateRequest.put("id", notificationId.intValue());
            updateRequest.put("isRead", true);
            
            ResponseEntity<JsonResult<?>> result = notificationFeignService.updateNotification(updateRequest);
            if (result.getBody() != null && result.getBody().isSuccess()) {
                log.info("标记通知已读成功: notificationId={}, userId={}", notificationId, currentUser.getId());
                return JsonResult.success("标记成功");
            } else {
                return JsonResult.fail(result.getBody() != null ? result.getBody().getMsg() : "标记失败");
            }

        } catch (Exception e) {
            log.error("标记通知已读失败: notificationId={}", notificationId, e);
            return JsonResult.fail("标记失败: " + e.getMessage());
        }
    }

    /**
     * 标记所有通知为已读
     */
    @PostMapping("/notifications/mark-all-read")
    @ResponseBody
    public JsonResult<?> markAllAsRead(HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            LoginUserVO user = getCurrentUser(request);
            if (user == null) {
                return JsonResult.fail("请先登录");
            }
            
            // 注意：当前NotificationFeignService没有markAllAsRead方法
            // 这里暂时返回成功，实际需要实现批量标记API或循环调用单个标记API
            log.info("标记所有通知已读请求: userId={}", user.getId());
            return JsonResult.success("全部标记成功");

        } catch (Exception e) {
            log.error("标记所有通知已读失败", e);
            return JsonResult.fail("标记失败: " + e.getMessage());
        }
    }

    /**
     * 删除通知
     */
    @PostMapping("/notifications/delete")
    @ResponseBody
    public JsonResult<?> deleteNotification(@RequestParam("notificationId") Long notificationId, HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            ResponseEntity<JsonResult<?>> result = notificationFeignService.deleteNotifications(
                    java.util.Arrays.asList(notificationId.intValue()));
            if (result.getBody() != null && result.getBody().isSuccess()) {
                log.info("删除通知成功: notificationId={}, userId={}", notificationId, currentUser.getId());
                return JsonResult.success("删除成功");
            } else {
                return JsonResult.fail(result.getBody() != null ? result.getBody().getMsg() : "删除失败");
            }

        } catch (Exception e) {
            log.error("删除通知失败: notificationId={}", notificationId, e);
            return JsonResult.fail("删除失败: " + e.getMessage());
        }
    }

    /**
     * 从Session中获取当前用户
     */
    private LoginUserVO getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object userInfo = session.getAttribute("currentUser");
            if (userInfo instanceof LoginUserVO) {
                return (LoginUserVO) userInfo;
            }
        }
        return null;
    }
} 